package com.example.jwt;

import cn.hutool.json.JSONUtil;
import com.example.common.RedisCommon;
import com.example.common.RedisCommonEnum;
import com.example.dto.base.Result;
import com.example.exception.BusinessException;
import com.example.exception.CommonErrorCode;
import com.example.util.RedisCacheUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * @Classname AuthorizationTokenFilter
 * @Description TODO
 * @Version 1.0.0
 * @Date 2023/3/1 8:57
 * @Created by wlh12
 */
//@Component
//@WebFilter(description="身份认证过滤器",urlPatterns = "/**")
public class AuthorizationTokenFilter implements Filter {
    // 静态资源
    public static String[] STATIC_RESOURCES = {
            "/swagger",
            "/doc.html",
            "/webjars/",
            "/v2/api-docs",
            "/favicon.ico",
    };
    // 公开资源
    public static String[] PUBLIC_RESOURCE = {
            "/user/login"
    };
    @Autowired
    private RedisCacheUtil redisCacheUtil;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        boolean anyMatch = Arrays.stream(STATIC_RESOURCES).anyMatch(item -> uri.contains(item));
        if (anyMatch){
            filterChain.doFilter(request,response);
            return;
        }
        anyMatch = Arrays.stream(PUBLIC_RESOURCE).anyMatch(item -> item.contains(uri));
        if (anyMatch){
            filterChain.doFilter(request,response);
            return;
        }
        String token = request.getHeader("Authorization");
        if (StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }
        if (StringUtils.isBlank(token)){
            // 不存在
            errorToken(request,response, CommonErrorCode.NO_LOGIN);
            return;
        }
        String account;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            account = claims.getSubject();
        } catch (Exception e){
            errorToken(request,response,CommonErrorCode.NO_LOGIN);
            return;
        }
        Object userAccount = redisCacheUtil.get(RedisCommon.getRedisKey(RedisCommonEnum.ACCOUNT_TOKEN_KEY, account));
        if (userAccount==null){
            errorToken(request,response,CommonErrorCode.NO_LOGIN);
            return;
        }
        if (!token.equals(userAccount.toString())){
            errorToken(request,response,CommonErrorCode.NO_LOGIN);
            return;
        }
        ThreadLocalContent.setThreadAccount(account);
        filterChain.doFilter(request,response);
    }

    private void errorToken(HttpServletRequest request,HttpServletResponse response,CommonErrorCode errorCode){
        Result<Void> voidResult = new Result<>();
        voidResult.setMessage(errorCode.getMessage());
        voidResult.setStatus(false);
        voidResult.setCode(errorCode.getCode());
        String jsonStr = JSONUtil.toJsonStr(voidResult);
        try {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(jsonStr);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
